<template>
  <div>
    <el-divider content-position="center">大气参数</el-divider>
    <div
      style="
        display: flex;
        justify-content: flex-end;
        margin-bottom: 20px;
        margin-right: 20px;
      "
    >
      <el-button type="primary" size="mini" @click="handleSave">确认</el-button>
    </div>
    <!-- <el-table
      :data="ttaskEnvList"
      :row-class-name="rowDetailIndex"
      ref="tProductFailureDetail"
      max-height="300"
      border
    >
      <el-table-column label="序号" align="center" prop="index" width="50" />
      <el-table-column
        label="大气压力 kPa"
        prop="atmosphericPressure"
        min-width="150"
        show-overflow-tooltip
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="环境温度 ℃"
        prop="ambientTemperature"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="绝对温度 K"
        prop="absoluteTemperature"
        align="center"
        min-width="150"
        show-overflow-tooltip
      >
      </el-table-column>

      <el-table-column
        label="绝对湿度 mb"
        align="center"
        prop="absoluteHumidity"
        min-width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="相对湿度 %"
        align="center"
        prop="relativeHumidity"
        min-width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdateatmosphere(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDeleteatmosphere(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table> -->

    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="大气参数"
      :visible.sync="Open"
      width="800px"
      append-to-body
    >
      <el-form
        ref="forms"
        :model="forms"
        label-width="120px"
        :inline="true"
        class="addData"
      >
        <el-form-item label="大气压力 kPa" prop="atmosphericPressure">
          <el-input
            v-model="forms.atmosphericPressure"
            placeholder="请输入大气压力 kPa"
          />
        </el-form-item>
        <el-form-item label="环境温度 ℃" prop="ambientTemperature">
          <el-input
            v-model="forms.ambientTemperature"
            placeholder="请输入环境温度 ℃"
          />
        </el-form-item>
        <el-form-item label="绝对温度 K" prop="absoluteTemperature">
          <el-input
            v-model="forms.absoluteTemperature"
            placeholder="请输入绝对温度 K"
          />
        </el-form-item>
        <el-form-item label="绝对湿度 mb" prop="absoluteHumidity">
          <el-input
            v-model="forms.absoluteHumidity"
            placeholder="请输入绝对湿度 mb"
          />
        </el-form-item>
        <el-form-item label="相对湿度 %" prop="relativeHumidity">
          <el-input
            v-model="forms.relativeHumidity"
            placeholder="请输入相对湿度 %"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormatmosphere"
          >确 定</el-button
        >
        <el-button @click="cancelatmosphere">取 消</el-button>
      </div>
    </el-dialog>

    <div class="weather-table">
      <!-- 如需整页容器，可自己包一层 el-card -->
      <el-table
        :data="tableData"
        :span-method="spanMethod"
        border
        style="width: 100%"
        size="mini"
      >
        <!-- 左侧固定列：汽参数 -->
        <el-table-column prop="param" label="" width="110" align="center" />
        <el-table-column prop="titles" label="" align="center" />

        <el-table-column prop="unit" label="单位" width="90" align="center" />
        <el-table-column label="夏季平均" align="center" width="170">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.summer"
              size="mini"
              style="width: 130px !important"
            />
          </template>
        </el-table-column>

        <el-table-column label="冬季平均" align="center" width="170">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.winter"
              size="mini"
              style="width: 130px !important"
            />
          </template>
        </el-table-column>

        <el-table-column label="年平均" align="center" width="170">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.annual"
              size="mini"
              style="width: 130px !important"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      currentEditIndex: -1,
      ttaskEnvList: [],
      Open: false,
      forms: {},

      tableData: [
        {
          titles: "大气压力",
          param: "大气参数",
          unit: "kPa(a)",
          atmosphericPressure: "", // 夏季平均
          winter: "", // 冬季平均
          annual: "", // 年平均
          summer: "",
        },
        {
          titles: "大气温度",
          param: "大气参数",
          unit: "℃",
          atmosphericPressure: "",
          winter: "",
          annual: "",
          summer: "",
        },
        {
          titles: "大气温度",
          param: "大气参数",
          unit: "K",
          atmosphericPressure: "",
          winter: "",
          annual: "",
          summer: "",
        },
        {
          titles: "绝对湿度",
          param: "大气参数",
          unit: "mb",
          atmosphericPressure: "",
          winter: "",
          annual: "",
          summer: "",
        },
        {
          titles: "相对湿度",
          param: "大气参数",
          unit: "%",
          atmosphericPressure: "",
          winter: "",
          annual: "",
          summer: "",
        },
      ],
    };
  },
  props: {
    formData: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    formData: {
      immediate: true,
      deep: true,
      handler(newVal) {
        // 更新组件内部数据
        this.ttaskEnvList = JSON.parse(JSON.stringify(newVal));
        console.log(this.ttaskEnvList, "this.ttaskEnvList ");

        this.tableData = [
          {
            titles: "大气压力",
            param: "大气参数",
            unit: "kPa(a)",
            summer: this.ttaskEnvList[0].atmosphericPressure,
            winter: this.ttaskEnvList[1].atmosphericPressure, // 冬季平均
            annual: this.ttaskEnvList[2].atmosphericPressure, // 年平均
          },
          {
            titles: "大气温度",
            param: "大气参数",
            unit: "℃",
            summer: this.ttaskEnvList[0].ambientTemperature,
            winter: this.ttaskEnvList[1].ambientTemperature,
            annual: this.ttaskEnvList[2].ambientTemperature,
          },
          {
            titles: "大气温度",
            param: "大气参数",
            unit: "K",
            summer: this.ttaskEnvList[0].absoluteTemperature,
            winter: this.ttaskEnvList[1].absoluteTemperature,
            annual: this.ttaskEnvList[2].absoluteTemperature,
          },
          {
            titles: "绝对湿度",
            param: "大气参数",
            unit: "mb",
            summer: this.ttaskEnvList[0].absoluteHumidity,
            winter: this.ttaskEnvList[1].absoluteHumidity,
            annual: this.ttaskEnvList[2].absoluteHumidity,
          },
          {
            titles: "相对湿度",
            param: "大气参数",
            unit: "%",
            summer: this.ttaskEnvList[0].relativeHumidity,
            winter: this.ttaskEnvList[1].relativeHumidity,
            annual: this.ttaskEnvList[2].relativeHumidity,
          },
        ];
      },
    },
  },
  methods: {
    handleSave() {
      let newdata = [
        {
          envName: "夏季平均",
          atmosphericPressure: this.tableData[0].summer,
          ambientTemperature: this.tableData[1].summer,
          absoluteTemperature: this.tableData[2].summer,
          absoluteHumidity: this.tableData[3].summer,
          relativeHumidity: this.tableData[4].summer,
        },
        {
          envName: "冬季平均",
          atmosphericPressure: this.tableData[0].winter,
          ambientTemperature: this.tableData[1].winter,
          absoluteTemperature: this.tableData[2].winter,
          absoluteHumidity: this.tableData[3].winter,
          relativeHumidity: this.tableData[4].winter,
        },
        {
          envName: "年平均",
          atmosphericPressure: this.tableData[0].annual,
          ambientTemperature: this.tableData[1].annual,
          absoluteTemperature: this.tableData[2].annual,
          absoluteHumidity: this.tableData[3].annual,
          relativeHumidity: this.tableData[4].annual,
        },
      ];
      // [{
      //   envName:'夏季',
      //   atmosphericPressure:this.tableData[0].summer
      //   ambientTemperature:this.tableData[1].summer
      //   absoluteTemperature:this.tableData[2].summer
      //   absoluteHumidity:this.tableData[3].summer
      //   relativeHumidity:this.tableData[4].summer
      // }]
      //  [{
      //   envName:'冬季',
      //   atmosphericPressure:this.tableData[0].winter
      //   ambientTemperature:this.tableData[1].winter
      //   absoluteTemperature:this.tableData[2].winter
      //   absoluteHumidity:this.tableData[3].winter
      //   relativeHumidity:this.tableData[4].winter
      // }]
      //  [{
      //   envName:'年',
      //   atmosphericPressure:this.tableData[0].annual
      //   ambientTemperature:this.tableData[1].annual
      //   absoluteTemperature:this.tableData[2].annual
      //   absoluteHumidity:this.tableData[3].annual
      //   relativeHumidity:this.tableData[4].annual
      // }]

      this.$emit("getTtaskEnvList", newdata);
      this.Open = false;
      this.resetform();
    },
    /* 合并单元格规则：完全还原图中效果 */
    spanMethod({ row, column, rowIndex, columnIndex }) {
      // 第一列：param 列，全部合并
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          return { rowspan: this.tableData.length, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 }; // 其余行不显示
        }
      }

      // 第二列：titles 列，合并第2、3行（索引1和2）
      if (columnIndex === 1) {
        if (rowIndex === 1) {
          return { rowspan: 2, colspan: 1 };
        } else if (rowIndex === 2) {
          return { rowspan: 0, colspan: 0 };
        }
      }

      // 其他列默认不合并
      return { rowspan: 1, colspan: 1 };
    },
    rowDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    handleAddatmosphere() {
      this.Open = true;
      this.currentEditIndex = -1;
      this.resetform();
    },
    // 修改
    handleUpdateatmosphere(row) {
      this.Open = true;
      this.forms = { ...row };

      // 查找当前编辑项的索引
      if (row.id) {
        this.currentEditIndex = this.ttaskEnvList.findIndex(
          (item) => item.id === row.id
        );
      } else {
        this.currentEditIndex = this.ttaskEnvList.findIndex((item) =>
          this.isSameRow(item, row)
        );
      }
    },

    // 删除
    handleDeleteatmosphere(row) {
      this.$confirm("确认删除大气参数?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.id) {
            // 根据ID删除
            const index = this.ttaskEnvList.findIndex(
              (item) => item.id === row.id
            );
            if (index !== -1) {
              this.ttaskEnvList.splice(index, 1);
            }
          } else {
            // 没有ID，根据索引删除
            const index = this.ttaskEnvList.findIndex((item) =>
              this.isSameRow(item, row)
            );
            if (index !== -1) {
              this.ttaskEnvList.splice(index, 1);
            }
          }
          this.$message.success("删除成功!");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    resetform() {
      this.forms = {
        atmosphericPressure: undefined,
        ambientTemperature: undefined,
        absoluteTemperature: undefined,
        relativeHumidity: undefined,
      };
    },
    // 生成临时ID
    generateTempId() {
      return "temp_" + Date.now() + Math.floor(Math.random() * 1000);
    },
    // 判断两行数据是否相同
    isSameRow(row1, row2) {
      const keys = Object.keys(row1);
      return keys.every((key) => row1[key] === row2[key]);
    },
    submitFormatmosphere() {
      this.$refs.forms.validate((valid) => {
        if (valid) {
          const formData = { ...this.forms };
          if (!this.ttaskEnvList) {
            this.ttaskEnvList = [];
          }
          if (this.currentEditIndex === -1) {
            // 新增操作
            if (!formData.id) {
              formData.temp_id = this.generateTempId(); // 为新增数据生成临时ID
            }

            this.ttaskEnvList.push(formData);
          } else {
            // 修改操作
            if (formData.id) {
              // 根据ID修改
              const index = this.ttaskEnvList.findIndex(
                (item) => item.id === formData.id
              );
              if (index !== -1) {
                this.ttaskEnvList.splice(index, 1, formData);
              }
            } else {
              // 没有ID，根据行数据匹配修改
              this.ttaskEnvList.splice(this.currentEditIndex, 1, formData);
            }
          }
          this.$emit("getTtaskEnvList", this.ttaskEnvList);
          this.Open = false;
          this.resetform();
        }
      });
    },
    cancelatmosphere() {
      this.Open = false;
      this.currentEditIndex = -1;
      this.resetform();
    },
  },
};
</script>
<style scoped lang="scss"></style>
